package tree;

import com.sun.corba.se.spi.activation._ActivatorImplBase;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author way
 * @create 2025-02-13 16:23
 */
public class _501_findMode {
    ArrayList<Integer> resList;
    int maxCount;
    int count;
    TreeNode pre;

    public int[] findMode(TreeNode root) {
        resList = new ArrayList<>();
        maxCount = 0;
        count = 0;
        pre = null;
        deal(root);
        int[] res = new int[resList.size()];
        for (int i = 0; i < resList.size(); i++) {
            res[i] = resList.get(i);
        }
        return res;
    }

    private void deal(TreeNode root) {
        if (root == null) return;

        deal(root.left);

        int rootVal = root.val;
        if (pre == null || rootVal != pre.val) {
            count = 1;
        } else {
            count++;
        }

        if (count > maxCount) {
            resList.clear();
            resList.add(rootVal);
            maxCount = count;
        } else if (count == maxCount) {
            resList.add(rootVal);
        }

        pre = root;
        deal(root.right);
    }
}
